/**
 * 
 */
package org.hotpotmaterial.codegenn2.config.security.provider;

import java.util.ArrayList;

import org.hotpotmaterial.codegenn2.common.HmCodeGenConstants;
import org.hotpotmaterial.codegenn2.config.bean.LoginPrincipal;
import org.hotpotmaterial.codegenn2.config.security.service.IAccountTokenService;
import org.hotpotmaterial.codegenn2.entity.HmteamAccount;
import org.hotpotmaterial.codegenn2.service.IHmteamAccountService;
import org.hotpotmaterial.codegenn2.utils.AESUtil;
import org.hotpotmaterial.codegenn2.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * @author cakydeveloper
 * 注册用户认证
 */
public class RegistUserProvider implements AuthenticationProvider {

	@Autowired
	private IHmteamAccountService accountService;

	@Autowired
	private IAccountTokenService tokenService;

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		HmteamAccount account = null;
		// token
		String token = null;
		if (null != authentication.getCredentials() && null != authentication.getPrincipal()) {
			LoginPrincipal principal = (LoginPrincipal) authentication.getPrincipal();
			// 类型是否匹配
			if (!HmCodeGenConstants.LOGIN_TYPE_IS_REG.equals(principal.getType())) {
				return null;
			}
			// 查询账号是否存在
			account = accountService.findAccountByUsername(HmCodeGenConstants.LOGIN_TYPE_IS_REG,
					principal.getUsername());
			if (account != null) {
				// AES解密
				String plainPass = AESUtil.decrypt((String) authentication.getCredentials(),
						HmCodeGenConstants.AES_PASSWORD_TRANS_KEY);
				// md5加密
				String md5Pass = MD5Util.encrypt(plainPass);
				if (account.getPassword().equals(md5Pass)) {
					// 部分内容隐藏
					account.setPassword(null);
					token = tokenService.createToken(account);
					account.setAuthToken(token);
					account.setTraceId(principal.getTraceId());
				} else {
					throw new UsernameNotFoundException("[Password is not correct] >>>> " + principal.getTraceId());
				}
			} else {
				throw new UsernameNotFoundException("[User is not found] >>>> " + principal.getTraceId());
			}
		}
		return new UsernamePasswordAuthenticationToken(account, null, new ArrayList<>());
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return true;
	}

}
